<?php



// Include config file
include_once('./common.php');

// Connect to database
$link = dbConnect();

// Attempt to auth user with database
$user = auth($_POST['username'], $_POST['password']);

if($user == ""){
   	echo "output=badLogin";
	return;
}

// Fetch the current time
$posted = time();

//get the posts per page incase we need it after a reply
$postsPerPage = $_POST['postsPerPage'];

//get the userID of the username to use for the rest of the script
$userID =  $user['id'];

//update user's post count
$result = mysql_query("UPDATE ".TABLE_PREFIX."_users SET posts = posts + 1, lastOnline = $posted 
					  WHERE userID = $userID");

//check what type of post we are making
if(isset($_POST['postType'])){
	//clean up the forum and thread IDs
	$forumID = mysql_real_escape_string($_POST['forumID']);
	$threadID = mysql_real_escape_string($_POST['threadID']);
	
	//if a new post then set the thread ID
	if($_POST['postType'] == "postNew"){
		$threadID = insertThread($_POST['forumID']);
	}
	
}else{
	echo "output=generalError&error=Can not define threadID in createpost.php";
	return;
}

//insert a post
$postID = insertPost($threadID);

//start the file process if there is a file there
for($i = 0; $i < $_POST['uploadImageCount']; $i++){
	//insert the reference in the dbase
	$result = mysql_query("INSERT INTO ".TABLE_PREFIX."_images 
						  (postID, imageLocation, description) 
						  VALUES ($postID, '".mysql_real_escape_string($_POST['file'.$i])."', '".mysql_real_escape_string($_POST['file'.$i."Description"])."')");
	if(!$result) {
		echo "output=mySqlError&error=".mysql_error();
		mysql_close($link);
		return;
	}
}

//set the update thread count var incase we don't need to update it
$updateThreadCount = "";

//update the forum based stats
if($_POST['postType'] == "postNew"){	
	//everything was good, sent it back to Flash
	echo "output=success&threadID=$threadID&page=1";
	$updateThreadCount = "threadCount = threadCount + 1, ";
}else{	
	//update the thread table
	$result = mysql_query("UPDATE ".TABLE_PREFIX."_threads 
						  SET replies = replies + 1, lastPost = $posted, lastUserID = $userID 
						  WHERE threadID = ".$threadID);
	if(!$result) {
		echo "output=mySqlError&error=".mysql_error();
		mysql_close($link);
		return;
	}
	
	//set up a quick query to get the total number of posts to send to flash
	$result = mysql_query("SELECT COUNT(*) AS postTotal 
							FROM ".TABLE_PREFIX."_posts 
							WHERE threadID = ".$threadID);
	if(!$result) {
		echo "output=mySqlError&error=".mysql_error();
		mysql_close($link);
		return;
	}
	
	$post = mysql_fetch_object($result);
	$totalPosts = $post->postTotal;
	$threadPage = ceil($totalPosts / $postsPerPage);
	
	echo "output=success&threadID=".$threadID."&page=".$threadPage;
	
	//see if anyone is subscribed to this thread
	handleSubscriptions($threadID);
}

// Build and execute query to update threadCount in forumForums table
$result = mysql_query("UPDATE ".TABLE_PREFIX."_forums 
					  SET ".$updateThreadCount."postCount = postCount + 1, lastUserID = $userID, lastPost = $posted, lastThreadID = $threadID 
					  WHERE forumID = ".$forumID);
if(!$result) {
	echo "output=mySqlError&error=".mysql_error();
	mysql_close($link);
	return;
}

// Close link to database server
mysql_close($link);

function insertThread($forumID){
	//set the globals
	global $posted, $userID;
	
	//insert the new thread
	$subject = mysql_real_escape_string($_POST['subject']);
	$result = mysql_query("INSERT INTO ".TABLE_PREFIX."_threads 
						  (userID, topic, lastPost, readMode, lastUserID, forumID) 
						  VALUES ($userID, '$subject', $posted, ".mysql_real_escape_string($_POST['isForumRestricted']).", $userID, ".$forumID.")");
	if(!$result){
		echo "output=mySqlError&error=".mysql_error();
		return;
	}
	
	// Fetch the threadID of the new thread
	$threadID = mysql_insert_id();
	
	return $threadID;
}

function insertPost($threadID){
	//set the globals
	global $posted, $userID;
	
	$message = mysql_real_escape_string($_POST['message']);
	
	// Build and execute query to insert new post
	$result = mysql_query("INSERT INTO ".TABLE_PREFIX."_posts 
						  (threadID, userID, message, emoticons, posted, userImage) 
						  VALUES($threadID, $userID, '$message', ".mysql_real_escape_string($_POST['emoticons']).", $posted, ".mysql_real_escape_string($_POST['uploadImageCount']).")");
	if(!$result){
		echo "output=mySqlError&error=".mysql_error();
		return;
	}
	
	//get the new postID to reference the image
	$postID = mysql_insert_id();
	
	return $postID;
}

function handleSubscriptions($threadID){
	global $userID;
	
	//get the status from flash
	if($_POST['subscribe'] != ""){
		//user would like to subscribe
		$result = mysql_query("REPLACE INTO ".TABLE_PREFIX."_subscriptions (userID, threadID) VALUES ($userID, $threadID)");
		
		if(!$result){
			echo "output=mySqlError&error=".mysql_error();
			return;
		}
	}else{
		//they would like to be removed from the subscription list (or not inserted)
		$result = mysql_query("DELETE FROM ".TABLE_PREFIX."_subscriptions WHERE userID = $userID AND threadID = $threadID");
		
		if(!$result){
			echo "output=mySqlError&error=".mysql_error();
			return;
		}
	}
	
	//this will check the database and figure out who needs to be notified of this reply
	$result = mysql_query("SELECT u.username, u.email, u2.username AS poster, t.topic
							FROM ".TABLE_PREFIX."_users u, ".TABLE_PREFIX."_users u2, ".TABLE_PREFIX."_subscriptions s, ".TABLE_PREFIX."_threads t
							WHERE s.threadID = $threadID
							AND s.userID != $userID
							AND t.threadID = s.threadID
							AND u.userID = s.userID
							AND u2.userID = $userID");
	if(!$result){
		echo "output=mySqlError&error=".mysql_error();
		return;
	}
	
	$message = $_POST['message'];
	
	//if everything went well go nuts and email these fine people
	while($data = mysql_fetch_object($result)){
		//fire off the message
		$mailMessage = $_POST['replyMessage']."\n\n".$_POST['installDirectory']."#/?t=$threadID"."\n\n-----------------\n".$message;
		sendMail($data->email, $data->topic." ".$_POST['update'], $mailMessage, $_POST['boardName'], $_POST['boardEmail']);
	}
}
?>